﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Enyim.Caching;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SilenthinkContract;
using Web.Areas.Auction.Models;
using Web.Controllers;

namespace Web.Areas.Auction.Controllers
{
    public class ListController : Controller
    {
        private readonly IAuctionService auctionService;
        public ListController(IAuctionService auctionService)
        {
            this.auctionService = auctionService;
        }

        public ActionResult Index()
        {
            var model = new ListControllerModel.Index();
            var auctions = auctionService.GetAllAuction();
            model.Auctions= auctions;
            model.JsonAuctions = JsonAuction(auctions);
            return View(model);
        }

        private IHtmlString JsonAuction(IEnumerable<SilenthinkContract.Domain.Auction> auctions)
        {
            var result= auctions.ToDictionary(o=>o.Id, o => new { BeginTime = o.StartDateTime, o.ExpectedTime, UserId = o.UserId, NickName = o.NickName, o.Id, o.Interval, o.BuyPrice, o.Status, Remain = o.ExpectedTime.HasValue ? DateDiff(o.ExpectedTime.Value) : o.Interval });

            var data = JsonConvert.SerializeObject(result, new JavaScriptDateTimeConverter());
            return new HtmlString(data);

        }
        private static int DateDiff(DateTime dateTime)
        {
            return (int)dateTime.Subtract(DateTime.Now).TotalSeconds;
        }
        private static string JavaScript(IList<SilenthinkContract.Domain.Auction> auctions)
        {
            var sb = new StringBuilder();
            sb.Append("var auction={");
            sb.AppendFormat("Status:{0},", DateTime.Now.Hour >= 10 ? "true" : "false");
            sb.Append("Data:{0}");
            sb.Append("}");
            return sb.ToString();
        }
    }
}
